import React from 'react';
import { Modal, Form, Input, message } from 'antd';
import { PWD_REG } from '@/utils/const';
import { resetUserPwd } from '@/services/public';

const layout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 18,
  },
};

const ResetPwdModal = (props) => {
  const { handleClose, userData } = props;
  const { id: userId, userName } = userData;
  const [form] = Form.useForm();

  const handleFormFieldChange = (changedFields, allFields) => {
    const changeName = changedFields[0].name;
    const passWd = allFields.filter((item) => item.name.includes('passWd'))[0].value;
    const passWdConfirm = allFields.filter((item) => item.name.includes('passWdConfirm'))[0].value;

    if (PWD_REG.test(passWd) && PWD_REG.test(passWdConfirm)) {
      if (passWd !== passWdConfirm) {
        form.setFields([{ name: changeName[0], errors: ['密码与确认密码不一致'] }]);
      }
    }
  };

  const handleSubmit = () => {
    form.validateFields().then((values) => {
      const { passWd } = values;
      resetUserPwd({ userId, passwd: passWd }).then(({ code, message: errMsg }) => {
        if (code === 0) {
          message.success('密码重置成功');
          handleClose();
        } else {
          message.error(errMsg);
        }
      });
    });
  };

  return (
    <Modal title="重置密码" visible width={600} onOk={handleSubmit} onCancel={handleClose}>
      <Form form={form} {...layout} onFieldsChange={handleFormFieldChange}>
        <Form.Item label="用户名" name="username" initialValue={userName}>
          <Input disabled />
        </Form.Item>
        <Form.Item
          label="密码"
          name="passWd"
          rules={[
            { required: true },
            {
              pattern: PWD_REG,
              message: '密码格式不正确，请重新输入',
            },
          ]}
        >
          <Input.Password placeholder="至少8位，由数字、字母或特殊字符中2种方式组成" />
        </Form.Item>
        <Form.Item
          label="确认密码"
          name="passWdConfirm"
          rules={[
            { required: true },
            {
              pattern: PWD_REG,
              message: '确认密码格式不正确，请重新输入',
            },
          ]}
        >
          <Input.Password placeholder="至少8位，由数字、字母或特殊字符中2种方式组成" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ResetPwdModal;
